<script setup lang="ts">
import { ref, reactive, defineProps, defineEmits, computed } from "vue";
import { ElMessageBox } from "element-plus";
import EmptyState from "@/components/common/EmptyState.vue";
import LoadingSpinner from "@/components/common/LoadingSpinner.vue";

// 定义订单状态接口
interface OrderStatus {
  value: string;
  label: string;
  type: "" | "primary" | "success" | "warning" | "danger" | "info";
}

// 定义订单项接口
interface OrderItem {
  productId: string;
  productName: string;
  productImage: string;
  price: number;
  quantity: number;
}

// 定义订单接口
interface Order {
  id: string;
  orderNo: string;
  userId: string;
  userName: string;
  userPhone: string;
  storeId: string;
  storeName: string;
  status: string;
  totalAmount: number;
  items: OrderItem[];
  address: string;
  createTime: string;
  payTime?: string;
  deliveryTime?: string;
  completeTime?: string;
  remark?: string;
}

const props = defineProps({
  orders: {
    type: Array as () => Order[],
    default: () => [],
  },
  loading: {
    type: Boolean,
    default: false,
  },
  total: {
    type: Number,
    default: 0,
  },
  currentPage: {
    type: Number,
    default: 1,
  },
  pageSize: {
    type: Number,
    default: 10,
  },
});

const emit = defineEmits([
  "page-change",
  "view-detail",
  "accept-order",
  "reject-order",
  "deliver-order",
  "cancel-order",
]);

// 订单状态列表
const orderStatusList = reactive<OrderStatus[]>([
  { value: "PENDING_PAYMENT", label: "待支付", type: "info" },
  { value: "PENDING_CONFIRM", label: "待确认", type: "primary" },
  { value: "PENDING_DELIVERY", label: "待配送", type: "warning" },
  { value: "DELIVERING", label: "配送中", type: "warning" },
  { value: "COMPLETED", label: "已完成", type: "success" },
  { value: "CANCELLED", label: "已取消", type: "danger" },
  { value: "REJECTED", label: "已拒绝", type: "danger" },
]);

// 获取订单状态显示信息
const getOrderStatusInfo = (status: string) => {
  return (
    orderStatusList.find((item) => item.value === status) || {
      value: status,
      label: status,
      type: "info",
    }
  );
};

// 处理页面变化
const handlePageChange = (page: number) => {
  emit("page-change", page);
};

// 查看订单详情
const handleViewDetail = (order: Order) => {
  emit("view-detail", order);
};

// 接受订单
const handleAcceptOrder = (order: Order) => {
  ElMessageBox.confirm("确定接受该订单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info",
  })
    .then(() => {
      emit("accept-order", order);
    })
    .catch(() => {});
};

// 拒绝订单
const handleRejectOrder = (order: Order) => {
  ElMessageBox.prompt("请输入拒绝原因", "拒绝订单", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /\S+/,
    inputErrorMessage: "拒绝原因不能为空",
  })
    .then(({ value }) => {
      emit("reject-order", order, value);
    })
    .catch(() => {});
};

// 配送订单
const handleDeliverOrder = (order: Order) => {
  ElMessageBox.confirm("确定该订单开始配送吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info",
  })
    .then(() => {
      emit("deliver-order", order);
    })
    .catch(() => {});
};

// 取消订单
const handleCancelOrder = (order: Order) => {
  ElMessageBox.prompt("请输入取消原因", "取消订单", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /\S+/,
    inputErrorMessage: "取消原因不能为空",
  })
    .then(({ value }) => {
      emit("cancel-order", order, value);
    })
    .catch(() => {});
};

// 格式化时间
const formatDate = (dateString: string) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleString();
};
</script>

<template>
  <div class="order-list-container">
    <LoadingSpinner v-if="loading" />

    <template v-else>
      <div v-if="orders && orders.length > 0" class="order-list">
        <el-card
          v-for="order in orders"
          :key="order.id"
          class="order-item"
          shadow="hover"
        >
          <div class="order-header">
            <div class="order-info">
              <span class="order-no">订单号：{{ order.orderNo }}</span>
              <span class="order-time"
                >下单时间：{{ formatDate(order.createTime) }}</span
              >
            </div>
            <div class="order-status">
              <el-tag :type="getOrderStatusInfo(order.status).type">
                {{ getOrderStatusInfo(order.status).label }}
              </el-tag>
            </div>
          </div>

          <div class="order-content">
            <div class="order-products">
              <div
                v-for="(item, index) in order.items"
                :key="index"
                class="product-item"
              >
                <el-image
                  :src="item.productImage"
                  fit="cover"
                  class="product-image"
                  :preview-src-list="[item.productImage]"
                >
                  <template #error>
                    <div class="image-placeholder">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="product-info">
                  <div class="product-name">{{ item.productName }}</div>
                  <div class="product-price">
                    ¥{{ item.price.toFixed(2) }} × {{ item.quantity }}
                  </div>
                </div>
              </div>
            </div>

            <div class="order-summary">
              <div class="order-total">
                <span
                  >共{{
                    order.items.reduce((sum, item) => sum + item.quantity, 0)
                  }}件商品</span
                >
                <span
                  >总计：<span class="price"
                    >¥{{ order.totalAmount.toFixed(2) }}</span
                  ></span
                >
              </div>

              <div class="order-actions">
                <el-button size="small" @click="handleViewDetail(order)"
                  >查看详情</el-button
                >

                <template v-if="order.status === 'PENDING_CONFIRM'">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleAcceptOrder(order)"
                    >接受订单</el-button
                  >
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleRejectOrder(order)"
                    >拒绝订单</el-button
                  >
                </template>

                <template v-if="order.status === 'PENDING_DELIVERY'">
                  <el-button
                    type="warning"
                    size="small"
                    @click="handleDeliverOrder(order)"
                    >开始配送</el-button
                  >
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleCancelOrder(order)"
                    >取消订单</el-button
                  >
                </template>
              </div>
            </div>
          </div>

          <div class="order-footer">
            <div class="customer-info">
              <span>收货人：{{ order.userName }}</span>
              <span>联系电话：{{ order.userPhone }}</span>
            </div>
            <div class="address-info">
              <span>收货地址：{{ order.address }}</span>
            </div>
            <div v-if="order.remark" class="remark-info">
              <span>备注：{{ order.remark }}</span>
            </div>
          </div>
        </el-card>

        <div class="pagination-container">
          <el-pagination
            v-if="total > 0"
            background
            layout="prev, pager, next, sizes"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
          />
        </div>
      </div>

      <EmptyState
        v-else
        text="暂无订单数据"
        description="当前没有符合条件的订单"
      />
    </template>
  </div>
</template>

<style scoped>
.order-list-container {
  width: 100%;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-item {
  margin-bottom: 16px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.order-info {
  display: flex;
  gap: 16px;
}

.order-no {
  font-weight: bold;
}

.order-time {
  color: #606266;
}

.order-content {
  padding: 16px 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-products {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.product-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  color: #909399;
}

.product-info {
  flex: 1;
}

.product-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.product-price {
  color: #606266;
  font-size: 14px;
}

.order-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px dashed #ebeef5;
}

.order-total {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.price {
  font-weight: bold;
  color: #ff6b00;
  font-size: 16px;
}

.order-actions {
  display: flex;
  gap: 8px;
}

.order-footer {
  padding-top: 12px;
  border-top: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.customer-info {
  display: flex;
  gap: 16px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
</style>
